package collection.test.chatroom;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**客户端*/
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("等待服务端连接....");
            socket = new Socket("localhost",8088);//创建socket
            System.out.println("连接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run(){
        try {
            //向服务端发送数据
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bos = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bos,true);
            Scanner scan = new Scanner(System.in);

            ReceiveMessage rm = new ReceiveMessage();
            Thread thread = new Thread(rm);
            thread.setDaemon(true);//设置为守护线程,避免异常:java.net.SocketException: Socket closed
            thread.start();

            String line;
            while (true){
                line = scan.nextLine();
                if ("exit".equals(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //四次挥手
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class ReceiveMessage implements Runnable{
        @Override
        public void run() {
            //接收服务端的数据
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine())!= null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        client.run();
    }
}
